#include "driver_key.h"
#include "input_sys.h"
#include "input_key.h"
#include "input_queue.h"
#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"
#include <stdio.h>

static TimerHandle_t key1_time;
static TimerHandle_t key2_time;
void vTimerCallback( TimerHandle_t xTimer );


void KEY_GPIO_Init(void)
{
     GPIO_InitTypeDef GPIO_InitStruct = {0};
     __HAL_RCC_GPIOA_CLK_ENABLE();

     GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
     GPIO_InitStruct.Pull = GPIO_PULLUP;
     
     GPIO_InitStruct.Pin = KEY1_Pin;
     HAL_GPIO_Init(KEY1_GPIO_Port, &GPIO_InitStruct);
     
     GPIO_InitStruct.Pin = KEY2_Pin;
     HAL_GPIO_Init(KEY2_GPIO_Port, &GPIO_InitStruct); 

     HAL_NVIC_SetPriority(EXTI0_IRQn, 13, 0);
     HAL_NVIC_SetPriority(EXTI1_IRQn, 13, 0);
     HAL_NVIC_EnableIRQ(EXTI0_IRQn);
     HAL_NVIC_EnableIRQ(EXTI1_IRQn); 
     
    key1_time = xTimerCreate("keytimer", 100, pdFALSE, NULL, vTimerCallback);
    key2_time = xTimerCreate("keytimer", 100, pdFALSE, NULL, vTimerCallback); 
}


void vTimerCallback( TimerHandle_t xTimer )
{  
    inputEvent event;          
    if(xTimer == key1_time)
    {
        event.iKey_numb = K1_NUMB;
        event.iType = Type_Key;  
        PutInputEvent(&event);
        printf("%s:%s:%d:keynumb:%d", __FILE__, __FUNCTION__, __LINE__, event.iKey_numb);
    }
    else if(xTimer == key2_time)
    {
        event.iKey_numb = K2_NUMB;
        event.iType = Type_Key;        
        PutInputEvent(&event);
        printf("%s:%s:%d:keynumb:%d", __FILE__, __FUNCTION__, __LINE__, event.iKey_numb);
    }      
}


void EXTI0_IRQHandler(void)
{
//    printf("%s %s %d\r\n", __FILE__, __FUNCTION__, __LINE__);
    HAL_GPIO_EXTI_IRQHandler(KEY1_Pin);
}


void EXTI1_IRQHandler(void)
{
    HAL_GPIO_EXTI_IRQHandler(KEY2_Pin);
}


void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
    BaseType_t pxHigherPriorityTaskWoken = pdFALSE;
    if(GPIO_Pin == KEY1_Pin)
    {
        xTimerResetFromISR(key1_time, &pxHigherPriorityTaskWoken);
        portYIELD_FROM_ISR(&pxHigherPriorityTaskWoken);
    }
    else if(GPIO_Pin == KEY2_Pin)
    {
        xTimerResetFromISR(key2_time, &pxHigherPriorityTaskWoken);
        portYIELD_FROM_ISR(&pxHigherPriorityTaskWoken);
    }
}

